package sunyu.tools.activemq;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Component
public class ActiveMqTools {

    @Resource(name = "jmsTemplate")
    private JmsTemplate template;

    @Resource(name = "defaultActiveMQTopic")
    private Destination defaultActiveMQTopic;

    @Resource(name = "defaultActiveMQQueue")
    private Destination defaultActiveMQQueue;

    public void sendTopic(Destination destination, final String message) {
        if (null == destination) {
            destination = defaultActiveMQTopic;
        }
        sendText(destination, message);
    }

    public void sendQueue(Destination destination, final String message) {
        if (null == destination) {
            destination = defaultActiveMQQueue;
        }
        sendText(destination, message);
    }

    private void sendText(Destination destination, final String message) {
        template.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }

}
